using System.Runtime.Serialization;
using Microsoft.Xna.Framework;

namespace INdT.Sparta.Graphics.Animations
{
    public class SpartaAnimationGroup : SpartaAbstractAnimation
    {
        private SpartaList<SpartaAbstractAnimation> AnimationsList;
        private int ActiveAnimationsCount;

        public delegate void CompletedDelegate();
        public CompletedDelegate Completed;

        public SpartaAnimationGroup(CompletedDelegate callback)
        {
            AnimationsList = new SpartaList<SpartaAbstractAnimation>();
            ActiveAnimationsCount = 0;
            Completed = callback;
        }

        public override void Begin()
        {
            base.Begin();

            int count = AnimationsList.Count;
            SpartaAbstractAnimation[] animations = AnimationsList.Array;

            for (int i = 0; i < count; i++)
            {
                ActiveAnimationsCount++;
                animations[i].InternalFinished = CompletedAnimation;
                animations[i].Begin();
            }
        }

        private void CompletedAnimation()
        {
            ActiveAnimationsCount--;
            if (ActiveAnimationsCount == 0)
            {
                if (Completed != null)
                {
                    Completed();
                }
                if (InternalFinished != null)
                {
                    InternalFinished();
                }
            }
        }

        public void Add(SpartaAbstractAnimation animation)
        {
            AnimationsList.Add(animation);
        }

        public override void Update(GameTime gameTime)
        {
            int count = AnimationsList.Count;
            SpartaAbstractAnimation[] animations = AnimationsList.Array;
            for (int i = 0; i < count; i++)
            {
                animations[i].Update(gameTime);
            }
        }

        public override void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            SpartaAbstractAnimation[] animations = AnimationsList.Array;
            int count = AnimationsList.Count;
            for (int i = 0; i < count; i++)
            {
                animations[i].Dispose();
                animations[i] = null;
            }
            AnimationsList.Dispose();
            AnimationsList = null;
            base.Dispose();
        }
    }
}
